package GameDb.JDBC;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * 这是一个JDBC的工具类
 */
public class JDBCUtils{
    private static final String driverClassName;
    private static final String url;
    private static final String username;
    private static final String password;
    
    private static DataSource dataSource;

    static {
        Properties properties=new Properties();
        try {
            properties.load(new FileInputStream("src/main/resources/druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
        driverClassName=properties.getProperty("driverClassName");
        url=properties.getProperty("url");
        username=properties.getProperty("username");
        password=properties.getProperty("password");

//        Properties properties = new Properties();
//        properties.load(new FileInputStream("src/main/resources/druid.properties"));
    }
    public void loadDriver(){
        try {
            Class.forName(driverClassName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public Connection getConnection(){
        Connection conn=null;
        loadDriver();
        try {
            conn=DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public Connection getDruidConn() throws Exception {
        if(dataSource == null) {
            Properties properties = new Properties();
            properties.load(new FileInputStream("src/main/resources/druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        }

        return dataSource.getConnection();
    }

    public void release(PreparedStatement prep,Connection conn) throws SQLException {
        prep.close();
        conn.close();
    }

    public void release(ResultSet rs,PreparedStatement prep,Connection conn) throws SQLException {
        rs.close();
        prep.close();
        conn.close();
    }

    public void release(Statement statement,Connection conn) throws SQLException {
        statement.close();
        conn.close();
    }
}

